Skip to main content

Anonymous Function

Anonymous function is a type of function in which function does not have name. Normally we use function keyword, then name the function and then parentheses is added. In an anonymous function there will only a function keyword with parentheses.

One method to use an anonymous function is

var anonymousFn = function (a, b) {
console.log(a + b);
};
anonymousFn(2, 3);

A variable anonymousFn is declared, the function will be invoked when we call this variable.

Another method to use an anonymous function is

(function (c, d) {
console.log(c + d);
})(5, 5);

If you want to create a function that execute immediately after the declaration, use anonymous function like this.

Danger

For anonymous functions:

  • First declare the anonymous function definition.
  • Then invoke the anonymous function.
  • For named function, function can be invoked even before interpreter reads function definition as shown in the example below.
sum(3, 3);
function sum(a, b) {
console.log(a + b);
}
  • But if anonymous function is invoked before interpreter reads function definition. There shows error output sum is not a function.
sum(3, 3);

var sum = function (a, b) {
console.log(a + b);
};